package com.zyy.utils;

import com.zyy.pojo.Goods;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 类描述
 * @Author: zyy
 * @Date: 2023/05/12 17:59
 */
public class HtmlParseUtil {

    public static void main(String[] args) throws Exception {
        String url = "https://search.jd.com/Search?keyword=java";

        Document document = Jsoup.parse(new URL(url), 3000);

        Element element = document.getElementById("J_goodsList");
        Elements lis = element.getElementsByTag("li");

//        System.out.println(lis.first().getElementsByTag("img").eq(0));
        //<img width="220" height="220" data-img="1" data-lazy-img="//img13.360buyimg.com/n7/jfs/t1/45127/23/18435/95610/62b1aa67E75f87a5b/f8ecffdeb445e91a.jpg">

//        System.out.println(lis.first().getElementsByClass("p-price").eq(0));
        //<div class="p-price"><strong class="J_10051377996907" data-presale="0" data-done="1"> <em>￥</em><i data-price="10051377996907">100.00</i> </strong>
        //</div>

        for (Element li : lis) {
            String imgSrc = li.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = li.getElementsByClass("p-price").eq(0).text();
            String name = li.getElementsByClass("p-name").eq(0).text();
            System.out.println(imgSrc);
            System.out.println(price);
            System.out.println(name);
        }
    }

    /*public static void main(String[] args) throws Exception {
        List<Goods> goodsList = getGoodsList("java");
        for (Goods goods : goodsList) {
            System.out.println(goods);
        }
    }*/

    public static List<Goods> getGoodsList(String keyword) throws Exception {
        String url = "https://search.jd.com/Search?keyword=" + keyword;

        Document document = Jsoup.parse(new URL(url), 3000);

        Element goodsListElement = document.getElementById("J_goodsList");
        Elements liElements = goodsListElement.getElementsByTag("li");

        List<Goods> goodsList = new ArrayList<>();
        for (Element liElement : liElements) {
            String imgSrc = liElement.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = liElement.getElementsByClass("p-price").eq(0).text();
            String name = liElement.getElementsByClass("p-name").eq(0).text();

            Goods goods = new Goods(imgSrc, price, name);
            goodsList.add(goods);
        }
        return goodsList;
    }
}
